// Copyright by LunaSec (owned by Refinery Labs, Inc)
//
// Licensed under the Business Source License v1.1
// (the "License"); you may not use this file except in compliance with the
// License. You may obtain a copy of the License at
//
// https://github.com/lunasec-io/lunasec/blob/master/licenses/BSL-LunaTrace.txt
//
// See the License for the specific language governing permissions and
// limitations under the License.
package vulnerability

import (
	"encoding/json"
	"github.com/lunasec-io/lunasec/lunatrace/bsl/ingest-worker/pkg/vulnerability/advisory"
	"github.com/lunasec-io/lunasec/lunatrace/bsl/ingest-worker/pkg/vulnerability/schema"
	"github.com/lunasec-io/lunasec/lunatrace/gogen/gql"
	"github.com/rs/zerolog/log"
	"io/ioutil"
)

// TODO (cthompson) allow this code to be more flexible for different vulnerability formats.
func generateBulkVulnerabilityInsertQuery(advisorySourceName string, filenames []string) ([]*gql.Vulnerability_insert_input, error) {
	var (
		vulnerabilitiesInsert []*gql.Vulnerability_insert_input
	)

	for _, filename := range filenames {
		var (
			err               error
			content           []byte
			vulnerabilityBody *gql.Vulnerability_insert_input
		)

		content, err = ioutil.ReadFile(filename)

		if err != nil {
			log.Error().
				Err(err).
				Str("filename", filename).
				Msg("unable to read vulnerability file")
			return nil, err
		}

		var vulnerability schema.OsvSchema
		err = json.Unmarshal(content, &vulnerability)
		if err != nil {
			log.Error().
				Err(err).
				Str("filename", filename).
				Msg("unable to unmarshal file")
			return nil, err
		}

		vulnerabilityBody, err = advisory.MapOsvToGraphql(advisorySourceName, &vulnerability)
		if err != nil {
			log.Error().
				Err(err).
				Str("filename", filename).
				Msg("unable to map osv to graphql insert")
			return nil, err
		}

		vulnerabilitiesInsert = append(vulnerabilitiesInsert, vulnerabilityBody)
	}
	return vulnerabilitiesInsert, nil
}
